package quantity.trande.util

import cn.hutool.core.lang.func.Func
import java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.util.function.Consumer

const val location: String = """jdbc:sqlite:/Users/zhaoxiuhuan/IdeaProjects/quantify-trade/core/src/main/resources/trade.db"""
fun connect(): Connection {
    Class.forName("org.sqlite.JDBC")
    return DriverManager.getConnection(location)
        .also {
            println("connect $location successfully ...")
        }
}

fun <R> executeQuery(sql: String, mapping1: Func<ResultSet, List<R>>): List<R>? {
    val statement = connect().createStatement()
    val resultSet = statement.executeQuery(sql)
    val rList = mapping1.call(resultSet)
    statement.close()
    return rList
}

fun executeInsert(sql: String, preHandler: Consumer<PreparedStatement>): Int {
    val statement = connect().prepareStatement(sql)
    preHandler.accept(statement)
    statement.executeUpdate()
    if (statement.generatedKeys.next()) {
        return statement.generatedKeys.getInt(1)
    }
    return 0
}

